package simpledb;

import java.util.HashMap;
import java.util.Map;

/**
 * Knows how to compute some aggregate over a set of StringFields.
 */
public class StringAggregator implements Aggregator {


    int gbfield ;
    Type gbfieldtype ;
    int afield ;
    Op what ;


    /**
     * Aggregate constructor
     * @param gbfield the 0-based index of the group-by field in the tuple, or NO_GROUPING if there is no grouping
     * @param gbfieldtype the type of the group by field (e.g., Type.INT_TYPE), or null if there is no grouping
     * @param afield the 0-based index of the aggregate field in the tuple
     * @param what aggregation operator to use -- only supports COUNT
     * @throws IllegalArgumentException if what != COUNT
     */

    public StringAggregator(int gbfield, Type gbfieldtype, int afield, Op what) {
        // some code goes here

        this.gbfield = gbfield ;
        this.gbfieldtype =  gbfieldtype ;
        this.afield = afield ;
        this.what = what ;
    }


    //    select count(1) from a group by age ;
//    int  tempId =  -1  ;
    Map<Integer , Integer > aggrResultMap = new HashMap();
//    int stringCount  = 0 ;


    /**
     * Merge a new tuple into the aggregate, grouping as indicated in the constructor
     * @param tup the Tuple containing an aggregate field and a group-by field
     */
    public void merge(Tuple tup) {
        // some code goes here

        IntField gbField = (IntField)tup.getField( this.gbfield );
        int gbFieldId   = gbField.getValue() ;

        Integer gbFieldValue = aggrResultMap.get( gbFieldId ) ;

//        System.out.println( "merge：：：：" + tempId + "---" +  field.getValue() );

        if( this.gbfieldtype.equals( gbField.getType()) ){

            if( gbFieldValue ==  null ) {
//                第一次找到相关记录
                aggrResultMap.put( gbFieldId , 1 );
            }else {
//               group有多条记录
//                if( what.equals(Op.COUNT) ) {
                aggrResultMap.put(gbFieldId, gbFieldValue + 1);
//                }
            }
        }

        System.out.println( "-------------------------------------------------------" );
        System.out.println( "string merge =====" + tup + "===" +  aggrResultMap  );
    }


    /**
     * Create a DbIterator over group aggregate results.
     *
     * @return a DbIterator whose tuples are the pair (groupVal,
     *   aggregateVal) if using group, or a single (aggregateVal) if no
     *   grouping. The aggregateVal is determined by the type of
     *   aggregate specified in the constructor.
     */
    public DbIterator iterator() {
        // some code goes here
//        if( tupleDesc == null ) {
//            tupleDesc = tup.getTupleDesc() ;
//        }

        TupleDesc tupleDesc  =  Utility.getTupleDesc(2) ;
        return new StringGroupIterator( aggrResultMap  , tupleDesc ) ;


//        throw new UnsupportedOperationException("implement me");
    }

}
